<template>
  <div>
    <el-upload
      accept="image/png, image/jpeg"
      :class="{ disabled: value }"
      action="#"
      :file-list="fileList"
      list-type="picture-card"
      :on-remove="handleRemove"
      :on-preview="handlePreview"
      :http-request="handleUpdate"
    >
      <!-- <img :src="value" v-if="value"  /> -->
      <i class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
    <el-dialog title="图片预览" :visible="isShow" @close="isShow = false">
      <img width="400px" height="400px" :src="value" />
    </el-dialog>
  </div>
</template>

<script>
import COS from "cos-js-sdk-v5";
export default {
  name: "UploadImage",
  props: {
    value: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      isShow: false,
    };
  },
  computed: {
    fileList: {
      get() {
        return this.value ? [{ url: this.value }] : [];
      },
      set() {},
    },
  },
  methods: {
    handleRemove() {
      this.$emit("input", "");
    },
    // 预览图片
    handlePreview() {
      this.isShow = true;
    },
    // 上传
    handleUpdate({ file }) {
      // file:选择图片文件对象
      // 把选择的图片对象发至腾讯云服务器
      // 实例化 cos
      const cos = new COS({
        SecretId: "AKIDZIrCJFyGNJ2XmnaAYky0pQq4A30td9PR",
        SecretKey: "8B8tVvBi194lDRTIsCMLzWqIf7W2Qmsu",
      });
      // 调用方法上传
      //   cos.putObject(
      //     {
      //       Bucket: "jinghai-1317090664", //桶名
      //       Region: "ap-beijing", //地址
      //       Key: file.name, //文件名
      //       Body: file, //文件对象
      //     },
      //     (err, data) => {
      //       if (err) return this.$message.success("上传失败了");
      //       // 拿到上传成功的图片地址，同步到父组件中
      //       this.$emit("input", `https://${data.Location}`);
      //     }
      //   );
    },
  },
};
</script>

<style lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100%;
  height: 100%;
  line-height: 100%;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.disabled {
  .el-upload {
    display: none;
  }
}
</style>